// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Data;
using System.Text;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Data.SqlClient;

namespace InterpriseSuiteEcommerceCommon
{
    public class PollAnswer
    {
        public int Id;
        public string Answer;
        public int NumberOfVotes;
        public int Percent;

        public PollAnswer(int id, string answer, int numVotes)
        {
            Id = id;
            Answer = answer;
            NumberOfVotes = numVotes;
            Percent = 0;
        }
    }

    public class PollAnswers : List<PollAnswer>
    {
        private int _overAllNumVotes = 0;

        public int OverAllNumberOfVotes
        {
            get{ return _overAllNumVotes;}
        }

        public static PollAnswers GetAnswers(Poll poll, string languageCode, bool withNumberOfVotes)
        {
            PollAnswers answers = new PollAnswers();

            string getPollAnswersQuery =
            string.Format(
                "EcommerceGetPollAnswers @WebsiteCode = {0}, @PollID = {1}, @LanguageCode = {2}, @CurrentDate = {3}, @WithNumberOfVotes = {4}",
                DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                DB.SQuote(poll.PollID),
                DB.SQuote(languageCode),
                DB.SQuote(Localization.ToDBDateTimeString(DateTime.Now)),
                CommonLogic.IIF(withNumberOfVotes, "1", "0")
            );


            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, getPollAnswersQuery))
                {
                    while (reader.Read())
                    {
                        PollAnswer answer =
                        new PollAnswer(
                            DB.RSFieldInt(reader, "PollAnswerID"),
                            DB.RSField(reader, "Answer"),
                            DB.RSFieldInt(reader, "NumVotes")
                        );

                        answers.Add(answer);

                        answers._overAllNumVotes += answer.NumberOfVotes;
                    
                    }
                }
            }


            if (answers.Count > 0 && withNumberOfVotes)
            {
                int overAllNumberOfVotes = answers._overAllNumVotes;

                // compute the it's percentage relative to the other answer votes
                foreach (PollAnswer answer in answers)
                {
                    answer.Percent = (int)(((decimal)answer.NumberOfVotes / (decimal)overAllNumberOfVotes) * 100M);
                }
            }

            return answers;
        }
    }

	/// <summary>
	/// Summary description for Poll.
	/// </summary>
	public class Poll
	{
		private String m_PollID;
		private int m_SkinID;
		private String m_Name;
        private bool m_AnonsCanVote;
		private String m_LocaleSetting;
        private bool _isExpired = false;

        private Poll(string pollId, string question, bool anonCanVote, bool isExpired, int skinId, string localeSetting)
        {
            m_PollID = pollId;
            m_Name = question;
            m_AnonsCanVote = anonCanVote;
            m_SkinID = skinId;
            m_LocaleSetting = localeSetting;
            _isExpired = isExpired;
        }

        public string PollID
        {
            get { return m_PollID; }
        }

        public bool IsExpired
        {
            get { return _isExpired; }
        }

        public bool AnonsCanVote
        {
            get { return m_AnonsCanVote; }
        }

		public void RecordVote(Customer thisCustomer, int PollAnswerID)
		{
            if (!this.HasVoteBy(thisCustomer))
			{
                DB.ExecuteSQL(
                    String.Format(
                        "INSERT INTO EcommercePollVotingRecord(PollID, PollAnswerID, CustomerCode, CreatedOn, WebsiteCode, ContactCode) VALUES({0}, {1}, {2}, {3}, {4}, {5})", 
                        DB.SQuote(m_PollID), 
                        DB.SQuote(PollAnswerID.ToString()), 
                        DB.SQuote(thisCustomer.CustomerCode),
                        DB.SQuote(Localization.ToDBDateTimeString(DateTime.Now)),
                        DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                        DB.SQuote(thisCustomer.ContactCode)
                    )
                );
			}
		}

        public bool HasVoteBy(Customer thisCustomer)
        {
            string checkVoteRecordQuery = 
            string.Format(
                "SELECT COUNT(*) AS N FROM EcommercePollVotingRecord with (NOLOCK) WHERE PollID = {0} AND CustomerCode = {1} AND WebsiteCode = {2} AND ContactCode = {3}",
                DB.SQuote(m_PollID),
                DB.SQuote(thisCustomer.CustomerCode),
                DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                DB.SQuote(thisCustomer.ContactCode)
            );

            return DB.GetSqlN(checkVoteRecordQuery) > 0;
        }

		public String Display(Customer thisCustomer, bool ShowPollsLink)
		{
			StringBuilder tmpS = new StringBuilder(4096);
            string votes = string.Empty;

            if (!this.HasVoteBy(thisCustomer))
			{
                    tmpS.Append("<form method=\"POST\" action=\"pollvote.aspx\" name=\"Poll" + m_PollID.ToString() + "Form\" id=\"Poll" + m_PollID.ToString() + "Form\">");
                    tmpS.Append("<input type=\"hidden\" name=\"PollID\" value=\"" + HttpUtility.UrlEncode(m_PollID) + "\">");
                    tmpS.Append("<span class=\"PollTitle\">" + m_Name + CommonLogic.IIF(this.IsExpired, " " +  AppLogic.GetString("poll.cs.1", m_SkinID, thisCustomer.LocaleSetting) + " " , string.Empty ) + "</span><br/>");

                    PollAnswers answers = PollAnswers.GetAnswers(this, thisCustomer.LanguageCode, false);
                    foreach (PollAnswer answer in answers)
                    {
                        tmpS.Append("<input class=\"PollRadio\" type=\"radio\" value=\"" + HttpUtility.UrlEncode(answer.Id.ToString()) +
                        "\" name=\"Poll_" + HttpUtility.UrlEncode(m_PollID.ToString()) + "\"><span class=\"PollAnswer\">" + Security.HtmlEncode(answer.Answer) +
                        "</span><br/>");
                    }

                    tmpS.AppendFormat("<div align=\"center\"><input class=\"PollSubmit site-button content\" data-contentType=\"string resource\" data-contentKey=\"poll.cs.3\" data-contentValue=\"{0}\" type=\"submit\" value=\"{0}\" name=\"B1\"></div>", AppLogic.GetString("poll.cs.3", thisCustomer.SkinID, thisCustomer.LocaleSetting, true));
                    tmpS.Append("</form>");
			}
			else
			{
				tmpS.Append("<span class=\"PollTitle\">" + m_Name + "</span><br/>");
				tmpS.Append("<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">");
                PollAnswers answers = PollAnswers.GetAnswers(this, thisCustomer.LanguageCode, true);

                foreach (PollAnswer answer in answers)
                {
                    tmpS.Append("<tr>");
                    tmpS.Append("<td width=\"40%\" align=\"right\" valign=\"middle\"><span class=\"PollAnswer\">" + Security.HtmlEncode(answer.Answer) + ":&nbsp;</span></td>");
                    tmpS.Append("<td width=\"60%\" align=\"left\" valign=\"middle\"><img src=\"" + AppLogic.LocateImageURL("skins/skin_" + thisCustomer.SkinID.ToString() + "/images/pollimage.gif") + "\" align=\"absmiddle\" width=\"" + answer.Percent.ToString() + "%\" height=\"10\" border=\"0\"><span class=\"PollAnswer\"> (" + answer.Percent.ToString() + "%)</span></td>");
                    tmpS.Append("</tr>");
                    tmpS.Append("<tr><td colspan=\"2\"><img src=\"images/spacer.gif\" width=\"100%\" height=\"2\"></td></tr>");
                }

                if (answers.OverAllNumberOfVotes > 1)
                {
                    votes = AppLogic.GetString("poll.cs.4", m_SkinID, thisCustomer.LocaleSetting);
                }
                else
                {
                    votes = AppLogic.GetString("poll.cs.3", m_SkinID, thisCustomer.LocaleSetting);
                }

                tmpS.AppendFormat("<tr><td colspan=\"2\" align=\"center\"> {0} {1} </td></tr>", answers.OverAllNumberOfVotes, votes);

				tmpS.Append("</table>");
				if(ShowPollsLink)
				{
					tmpS.Append("  <div align=\"center\"><a class=\"PollLink\" href=\"polls.aspx\">" + AppLogic.GetString("poll.cs.2",m_SkinID,Thread.CurrentThread.CurrentUICulture.Name) + "</a></div>");
				}
			}
			return tmpS.ToString();
		}

        public static bool HasAnyPollNotVotedByThisCustomerYet(Customer thisCustomer)
        {
            return null != GetAnyPollNotVotedByThisCustomerYet(thisCustomer);
        }

        public static Poll GetAnyPollNotVotedByThisCustomerYet(Customer thisCustomer)
        {
            string pollsThatHasNeverBeenVotedByThisCustomerYetQuery = 
            string.Format(
                "EcommerceGetAnyPollNotVotedByCustomer @websiteCode = {0}, @CustomerCode = {1}, @IsRegistered = {2}, @LanguageCode = {3}, @CurrentDate = {4}, @ContactCode = {5}",
                DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode ),
                DB.SQuote(thisCustomer.CustomerCode),
                CommonLogic.IIF(thisCustomer.IsRegistered, "1", "0"),
                DB.SQuote(thisCustomer.LanguageCode),
                DB.SQuote(Localization.ToDBDateTimeString(DateTime.Now)),
                DB.SQuote(thisCustomer.ContactCode)
            );

            Poll anyPoll = null;

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, pollsThatHasNeverBeenVotedByThisCustomerYetQuery))
                {// were only interested in the first one...
                    if (reader.Read())
                    {
                        anyPoll =
                        new Poll(
                            DB.RSField(reader, "PollID"),
                            DB.RSField(reader, "Question"),
                            DB.RSFieldBool(reader, "AnonsCanVote"),
                            false, // of course, the poll shouldn't have expired yet
                            thisCustomer.SkinID,
                            thisCustomer.LocaleSetting
                        );
                    }
                }
            }

            return anyPoll;
        }

        public static Poll GetPoll(string pollId, Customer thisCustomer)
        {
            string getPollQuery =
            string.Format(
                "EcommerceGetPoll @WebsiteCode = {0}, @PollID = {1}, @LanguageCode = {2}, @IsRegistered = {3}, @CurrentDate = {4}",
                DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode ),
                DB.SQuote(pollId),
                DB.SQuote(thisCustomer.LanguageCode),
                CommonLogic.IIF(thisCustomer.IsRegistered, "1", "0"),
                DB.SQuote(Localization.ToDBDateTimeString(DateTime.Now))
            );

            Poll foundPoll = null;


            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, getPollQuery))
                {
                    if (reader.Read())
                    {
                        foundPoll = new Poll(
                            DB.RSField(reader, "PollID"),
                            DB.RSField(reader, "Question"),
                            DB.RSFieldBool(reader, "AnonsCanVote"),
                            DB.RSFieldBool(reader, "IsExpired"),
                            thisCustomer.SkinID,
                            thisCustomer.LocaleSetting
                        );
                    }
                }
            }

            return foundPoll;
        }

	}
}












